<?php


namespace EchoPHP\Http;

use EchoPHP\Foundation\Support\ResponseHeaderBag;
use Exception;

/**
 * HTTP 响应
 * 响应包括 状态行 响应报头 报文内容
 * 状态行 状态行由HTTP协议版本号， 状态码， 状态消息三部分组成
 * 响应报头 同请求报头类似，用户标记一些环境信息等
 * 报文内容 服务器返回的数据
 * @package EchoPHP\Http
 */
class Response {
    const HTTP_CONTINUE = 100;
    const HTTP_SWITCHING_PROTOCOLS = 101;
    const HTTP_PROCESSING = 102;            // RFC2518
    const HTTP_EARLY_HINTS = 103;           // RFC8297
    const HTTP_OK = 200;
    const HTTP_CREATED = 201;
    const HTTP_ACCEPTED = 202;
    const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
    const HTTP_NO_CONTENT = 204;
    const HTTP_RESET_CONTENT = 205;
    const HTTP_PARTIAL_CONTENT = 206;
    const HTTP_MULTI_STATUS = 207;          // RFC4918
    const HTTP_ALREADY_REPORTED = 208;      // RFC5842
    const HTTP_IM_USED = 226;               // RFC3229
    const HTTP_MULTIPLE_CHOICES = 300;
    const HTTP_MOVED_PERMANENTLY = 301;
    const HTTP_FOUND = 302;
    const HTTP_SEE_OTHER = 303;
    const HTTP_NOT_MODIFIED = 304;
    const HTTP_USE_PROXY = 305;
    const HTTP_RESERVED = 306;
    const HTTP_TEMPORARY_REDIRECT = 307;
    const HTTP_PERMANENTLY_REDIRECT = 308;  // RFC7238
    const HTTP_BAD_REQUEST = 400;
    const HTTP_UNAUTHORIZED = 401;
    const HTTP_PAYMENT_REQUIRED = 402;
    const HTTP_FORBIDDEN = 403;
    const HTTP_NOT_FOUND = 404;
    const HTTP_METHOD_NOT_ALLOWED = 405;
    const HTTP_NOT_ACCEPTABLE = 406;
    const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
    const HTTP_REQUEST_TIMEOUT = 408;
    const HTTP_CONFLICT = 409;
    const HTTP_GONE = 410;
    const HTTP_LENGTH_REQUIRED = 411;
    const HTTP_PRECONDITION_FAILED = 412;
    const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
    const HTTP_REQUEST_URI_TOO_LONG = 414;
    const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
    const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    const HTTP_EXPECTATION_FAILED = 417;
    const HTTP_I_AM_A_TEAPOT = 418;                                               // RFC2324
    const HTTP_MISDIRECTED_REQUEST = 421;                                         // RFC7540
    const HTTP_UNPROCESSABLE_ENTITY = 422;                                        // RFC4918
    const HTTP_LOCKED = 423;                                                      // RFC4918
    const HTTP_FAILED_DEPENDENCY = 424;                                           // RFC4918
    const HTTP_TOO_EARLY = 425;                                                   // RFC-ietf-httpbis-replay-04
    const HTTP_UPGRADE_REQUIRED = 426;                                            // RFC2817
    const HTTP_PRECONDITION_REQUIRED = 428;                                       // RFC6585
    const HTTP_TOO_MANY_REQUESTS = 429;                                           // RFC6585
    const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;                             // RFC6585
    const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451;
    const HTTP_INTERNAL_SERVER_ERROR = 500;
    const HTTP_NOT_IMPLEMENTED = 501;
    const HTTP_BAD_GATEWAY = 502;
    const HTTP_SERVICE_UNAVAILABLE = 503;
    const HTTP_GATEWAY_TIMEOUT = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;
    const HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506;                        // RFC2295
    const HTTP_INSUFFICIENT_STORAGE = 507;                                        // RFC4918
    const HTTP_LOOP_DETECTED = 508;                                               // RFC5842
    const HTTP_NOT_EXTENDED = 510;                                                // RFC2774
    const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511;                             // RFC6585

    /**
     * Status codes translation table.
     *
     * The list of codes is complete according to the
     * {@link http://www.iana.org/assignments/http-status-codes/ Hypertext Transfer Protocol (HTTP) Status Code Registry}
     * (last updated 2016-03-01).
     *
     * Unless otherwise noted, the status code is defined in RFC2616.
     *
     * @var array
     */
    public static $statusTexts = [
        100 => 'Continue',
        101 => 'Switching Protocols',
        102 => 'Processing',            // RFC2518
        103 => 'Early Hints',
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        207 => 'Multi-Status',          // RFC4918
        208 => 'Already Reported',      // RFC5842
        226 => 'IM Used',               // RFC3229
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        307 => 'Temporary Redirect',
        308 => 'Permanent Redirect',    // RFC7238
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Payload Too Large',
        414 => 'URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Range Not Satisfiable',
        417 => 'Expectation Failed',
        418 => 'I\'m a teapot',                                               // RFC2324
        421 => 'Misdirected Request',                                         // RFC7540
        422 => 'Unprocessable Entity',                                        // RFC4918
        423 => 'Locked',                                                      // RFC4918
        424 => 'Failed Dependency',                                           // RFC4918
        425 => 'Too Early',                                                   // RFC-ietf-httpbis-replay-04
        426 => 'Upgrade Required',                                            // RFC2817
        428 => 'Precondition Required',                                       // RFC6585
        429 => 'Too Many Requests',                                           // RFC6585
        431 => 'Request Header Fields Too Large',                             // RFC6585
        451 => 'Unavailable For Legal Reasons',                               // RFC7725
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        506 => 'Variant Also Negotiates',                                     // RFC2295
        507 => 'Insufficient Storage',                                        // RFC4918
        508 => 'Loop Detected',                                               // RFC5842
        510 => 'Not Extended',                                                // RFC2774
        511 => 'Network Authentication Required',                             // RFC6585
    ];

    /**
     * 响应头信息
     * @var ResponseHeaderBag
     */
    protected $headers;

    /**
     *
     * @var
     */
    protected $content;

    protected $version;

    protected $statusCode;
    protected $statusText;

    protected $charset;

    protected $exception;
    /**
     * jsonp回调名称
     * @var string
     */
    protected $callback;

    /**
     * 构造函数
     * Response constructor.
     * @param string $content
     * @param int $statusCode
     * @param array $headers
     */
    public function __construct($content = '', int $statusCode = 200, array $headers = []) {
        $this->headers = new ResponseHeaderBag($headers);
        $this->setContent($content);
        $this->setStatusCode($statusCode);
        $this->setProtocolVersion('1.1');
    }

    /**
     * 创建response 对象
     * @param string $content
     * @param int $statusCode
     * @param array $headers
     * @return Response
     */
    public static function create($content = '', int $statusCode = 200, array $headers = []) {
        return new static($content, $statusCode, $headers);
    }

    /**
     * 响应类的字符串格式  使用此方法注意一定要先调用prepare方法，将相关头信息等提前输出好
     * @return string
     */
    public function __toString() {
        return sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText) . "\r\n" .
            $this->headers . "\r\n" .
            $this->getContent();
    }

    /**
     * 发送响应前根据request请求修正一下传入错误的响应参数
     * @param Request $request
     * @return $this
     */
    public function prepare(Request $request) {
        $headers = $this->headers;
        //修正Content-Type 信息
        if ($this->isInformational() || $this->isEmpty()) {
            $this->setContent(null);
            $headers->remove('Content-Type');
            $headers->remove('Content-Length');
        } else {
            if (!$headers->has('Content-Type')) {
                $format = $request->getRequestFormat();
                if (null !== $format && $mimeType = $request->getMimeType($format)) {
                    $headers->set('Content-Type', $mimeType);
                }
            }

            //修正Content-Type 内容
            $contentType = $headers->get('Content-Type');
            $charset = $this->charset ?: 'UTF-8';
            if (!$contentType) {
                $headers->set('Content-Type', 'text/html; charset=' . $charset);
            } elseif (0 === stripos($contentType, 'text/') && false === stripos($contentType, 'charset')) {
                $headers->set('Content-Type', $contentType . '; charset=' . $charset);
            }
            //修正Content-Length
            if ($headers->has('Transfer-Encoding')) {
                $headers->remove('Content-Length');
            }
        }
        //修正HTTP protocol 协议版本
        if ('HTTP/1.0' == $request->server()->get('SERVER_PROTOCOL')) {
            $this->setProtocolVersion('1.0');
        }
        return $this;
    }

    /**
     * 设置头信息
     * @param $key
     * @param $value
     * @param bool $replace
     * @return $this
     */
    public function header($key, $value, $replace = true) {
        $this->headers->set($key, $value, $replace);
        return $this;
    }

    /**
     * 设置cookie
     * @param Cookie ...$cookies
     * @return $this
     */
    public function cookie(Cookie ...$cookies) {
        foreach ($cookies as $cookie) {
            $this->headers->setCookie($cookie);
        }

        return $this;
    }

    /**
     * 复制一个新的响应类实例
     */
    public function __clone() {
        $this->headers = clone $this->headers;
    }

    /**
     * 发送http响应
     * @return $this
     */
    public function send() {
        $this->sendHeaders();
        $this->sendContent();

        if (function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        } elseif (!in_array(PHP_SAPI, ['cli', 'phpdbg'], true)) {
            static::closeOutputBuffers(0, true);
        }

        return $this;
    }

    /**
     * 发送响应头
     * @return $this
     */
    public function sendHeaders() {
        //如果头信息已经发出，则不再重复发送
        if (headers_sent()) {
            return $this;
        }

        // headers
        foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) {
            $replace = 0 === strcasecmp($name, 'Content-Type');
            foreach ($values as $value) {
                if (true === $value) {
                    $value = 'true';
                } elseif (false === $value) {
                    $value = 'false';
                }
                header($name . ': ' . $value, $replace, $this->statusCode);
            }
        }

        // cookies
        foreach ($this->headers->getCookies() as $cookie) {
            header('Set-Cookie: ' . $cookie->getName() . strstr($cookie, '='), false, $this->statusCode);
        }

        // status
        header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode);
        return $this;
    }

    /**
     * 发送响应正文
     * @return $this
     */
    public function sendContent() {
        echo $this->content;
        return $this;
    }

    /**
     * 设置响应正文
     * @param $content
     * @return $this
     */
    public function setContent($content) {
        $this->content = $content;
        return $this;
    }

    /**
     * 获取响应正文
     * @return mixed
     */
    public function getContent() {
        return $this->content;
    }

    /**
     * 设置响应状态码及对应状态描述
     * @param $code
     * @param null $text
     * @return $this
     */
    public function setStatusCode($code, $text = null) {
        $this->statusCode = $code;
        if (is_null($text)) {
            $this->statusText = isset(self::$statusTexts[$code]) ? self::$statusTexts[$code] : 'unknow status';
            return $this;
        }
        $this->statusText = strval($text);
        return $this;
    }

    /**
     * 获取响应状态码
     * @return mixed
     */
    public function getStatusCode() {
        return $this->statusCode;
    }

    /**
     * 设置异常信息类
     * @param Exception $e
     * @return $this
     */
    public function setException(Exception $e) {
        $this->exception = $e;
        return $this;
    }

    /**
     * 设置http协议版本号，默认http 1.1
     * @param string $version
     */
    public function setProtocolVersion($version = '1.1') {
        $this->version = $version;
    }

    /**
     * 获取响应http协议版本
     * @return mixed
     */
    public function getProtocolVersion() {
        return $this->version;
    }

    /**
     * 设置响应类字符编码
     * @param $charset
     * @return $this
     */
    public function setCharset($charset) {
        $this->charset = $charset;
        return $this;
    }

    /**
     * 将之源头定义为公开类型
     * @return $this
     */
    public function setPublic() {
        $this->headers->addCacheControlDirective('public');
        $this->headers->removeCacheControllerDirective('private');

        return $this;
    }

    /**
     * 获取响应类字符编码
     * @return mixed
     */
    public function getCharset() {
        return $this->charset;
    }

    /**
     * 将输入缓冲区中的数据清除或者输出
     * @param int $targetLevel 处理到的缓冲机制嵌套级别
     * @param bool $flush 是否输出
     */
    public static function closeOutputBuffers(int $targetLevel, bool $flush) {
        //得到所有输出缓冲区的状态
        $status = ob_get_status(true);
        $level = count($status);
        $flags = PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE);

        while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) {
            if ($flush) {
                ob_end_flush();
            } else {
                ob_end_clean();
            }
        }
    }

    /**
     * 判断响应码是否在合法范围内
     * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
     *
     * @final
     */
    public function isInvalid(): bool {
        return $this->statusCode < 100 || $this->statusCode >= 600;
    }

    /**
     *  判断响应码是否是在[100, 200) 之间的返回请求状态信息的状态码
     * @final
     */
    public function isInformational(): bool {
        return $this->statusCode >= 100 && $this->statusCode < 200;
    }

    /**
     * 判断是否是[200, 300)之前的请求成功状态码
     * @final
     */
    public function isSuccessful(): bool {
        return $this->statusCode >= 200 && $this->statusCode < 300;
    }

    /**
     * 判断是否是跳转状态码 [300, 400)
     * @final
     */
    public function isRedirection(): bool {
        return $this->statusCode >= 300 && $this->statusCode < 400;
    }

    /**
     * 判断是否客户端错误 [400, 500)
     * @final
     */
    public function isClientError(): bool {
        return $this->statusCode >= 400 && $this->statusCode < 500;
    }

    /**
     * 判断是否服务端错误 [500, 600)
     * @final
     */
    public function isServerError(): bool {
        return $this->statusCode >= 500 && $this->statusCode < 600;
    }

    /**
     * 判断请求是否成功 200
     * @final
     */
    public function isOk(): bool {
        return 200 === $this->statusCode;
    }

    /**
     * 判断是否客户端禁止访问 403
     * @final
     */
    public function isForbidden(): bool {
        return 403 === $this->statusCode;
    }

    /**
     * 判断是否404 资源无法访问
     * @final
     */
    public function isNotFound(): bool {
        return 404 === $this->statusCode;
    }

    /**
     * 判断是否是重定向  需要验证状态码及重定向地址
     * @param string|null $location 重定向地址
     * @return bool
     * @final
     */
    public function isRedirect(string $location = null): bool {
        return \in_array($this->statusCode, [201, 301, 302, 303, 307, 308]) && (null === $location ?: $location == $this->headers->get('Location'));
    }

    /**
     * 判断是否是空内容
     * @final
     */
    public function isEmpty(): bool {
        return \in_array($this->statusCode, [204, 304]);
    }

    /**
     * 设置资源令牌
     * @param string|null $etag
     * @param bool $weak 弱验证符号
     * @return $this
     */
    public function setEtag(string $etag = null, bool $weak = false) {
        if (null === $etag) {
            $this->headers->remove('Etag');
        } else {
            if (0 !== strpos($etag, '"')) {
                $etag = '"' . $etag . '"';
            }

            $this->headers->set('ETag', (true === $weak ? 'W/' : '') . $etag);
        }

        return $this;
    }

    /**
     * 设置资源修改时间
     * @param \DateTimeInterface|null $date
     * @return $this
     */
    public function setLastModified(\DateTimeInterface $date = null) {
        if (null === $date) {
            $this->headers->remove('Last-Modified');

            return $this;
        }

        if ($date instanceof \DateTime) {
            $date = \DateTimeImmutable::createFromMutable($date);
        }

        $date = $date->setTimezone(new \DateTimeZone('UTC'));
        $this->headers->set('Last-Modified', $date->format('D, d M Y H:i:s') . ' GMT');

        return $this;
    }

    /**
     * Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9.
     *
     * @see http://support.microsoft.com/kb/323308
     *
     * @final
     */
    protected function ensureIEOverSSLCompatibility(Request $request) {
        if (false !== stripos($this->headers->get('Content-Disposition'), 'attachment') && 1 == preg_match('/MSIE (.*?);/i', $request->server()->get('HTTP_USER_AGENT'), $match) && true === $request->isSecure()) {
            if ((int)preg_replace('/(MSIE )(.*?);/', '$2', $match[0]) < 9) {
                $this->headers->remove('Cache-Control');
            }
        }
    }
}